package com.jiantong.work.impl.manager;

import com.google.common.collect.Maps;
import com.jiantong.common.util.UserUtil;
import com.jiantong.user.ext.LoginUser;
import com.jiantong.user.impl.dao.BreedFactoryDao;
import com.jiantong.user.impl.dao.BreedFactoryStableDao;
import com.jiantong.user.model.BreedFactory;
import com.jiantong.user.model.BreedFactoryStable;
import com.jiantong.work.enums.*;
import com.jiantong.work.impl.dao.*;
import com.jiantong.work.model.*;
import com.jiantong.work.util.Utils;
import org.assertj.core.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by niufei on 2017/3/20.
 * 生成无害化  尚未做  生成 生产记录(生效)
 */
@Component
public class BreedReportManager {

    private final BreedReportDao breedReportDao;

    private final ReportHandleResumeDao reportHandleResumeDao;

    private final BreedReportSurveyRecordDao breedReportSurveyRecordDao;

    private final ButcherAdmissionInspectionDao butcherAdmissionInspectionDao;

    private final HarmlessDao harmlessDao;

    private final ProductionReportDao productionReportDao;

    private final AnimalMarkDao animalMarkDao;

    private final BreedFactoryDao breedFactoryDao;

    private final BreedFactoryStableDao breedFactoryStableDao;

    @Autowired
    public BreedReportManager(BreedReportDao breedReportDao, ReportHandleResumeDao reportHandleResumeDao,
                              BreedReportSurveyRecordDao breedReportSurveyRecordDao,
                              ButcherAdmissionInspectionDao butcherAdmissionInspectionDao,
                              HarmlessDao harmlessDao,
                              ProductionReportDao productionReportDao,
                              AnimalMarkDao animalMarkDao,
                              BreedFactoryDao breedFactoryDao,
                              BreedFactoryStableDao breedFactoryStableDao) {
        this.breedReportDao = breedReportDao;
        this.reportHandleResumeDao = reportHandleResumeDao;
        this.breedReportSurveyRecordDao = breedReportSurveyRecordDao;
        this.butcherAdmissionInspectionDao = butcherAdmissionInspectionDao;
        this.harmlessDao = harmlessDao;
        this.productionReportDao = productionReportDao;
        this.animalMarkDao = animalMarkDao;
        this.breedFactoryDao = breedFactoryDao;
        this.breedFactoryStableDao = breedFactoryStableDao;
    }

    /**
     * 产地检疫--养殖端新建单据
     * @param breedReport 产地检疫的对象
     * @param toStatus 到状态
     * @return Map<String ,Object>
     */
    @Transactional
    public Map<String , Object> createBreedReport(BreedReport breedReport, Integer toStatus){
        LoginUser loginUser = UserUtil.getCurrentUser();
        Integer fromStatus = breedReport.getStatus();
        Map<String , Object> map = Maps.newHashMap();
        String prefix = "N";
        prefix = Utils.createPrefix(prefix,loginUser);//单据编号前缀的开头字母 和 当前用户
        String number = Utils.create(prefix,breedReportDao.findCurrentMaxNumber(prefix));//要在表中拿到当前最大的Number号
        breedReport.setNumber(number);
        breedReport.setDeleteFlag(DocumentsDeleteFlag.NORMAL.value());
        if(toStatus != null && !fromStatus.equals(toStatus)){
            breedReport.setStatus(toStatus);
            breedReportDao.create(breedReport);
            map.put("breedReportId" ,breedReport.getId());

            ReportHandleResume reportHandleResume = new ReportHandleResume();
            reportHandleResume.setReportId(breedReport.getId());
            reportHandleResume.setReportNumber(breedReport.getNumber());
            reportHandleResume.setType(DocumentsType.QUARANTINE_ORIGIN_AREA.value());//0:代表产地检疫
            reportHandleResume.setUserId(loginUser.getId());
            reportHandleResume.setUserName(loginUser.getName());
            reportHandleResume.setFromStatus(fromStatus);
            reportHandleResume.setToStatus(toStatus);

            reportHandleResumeDao.create(reportHandleResume);
            map.put("reportHandleResumeId" ,reportHandleResume.getId());
        }else{
            breedReportDao.create(breedReport);
            map.put("breedReportId" ,breedReport.getId());
        }
        List<String> markNumbers = breedReport.getEarTagNumbers();
        if(markNumbers != null && !markNumbers.isEmpty()){
            Map<String , Object> map1 = Maps.newHashMap();
            map1.put("markNumbers",markNumbers);
            map1.put("isSelected",2);
            animalMarkDao.updateMarks(map1);
        }
        return map;
    }

    /**
     * 产地检疫--养殖端更新单据
     * @param breedReport 产地检疫的对象
     * @param toStatus 到状态
     * @return Map<String , Object>
     */
    @Transactional
    public Map<String , Object> updateBreedReport(BreedReport breedReport , Integer toStatus){
        LoginUser loginUser = UserUtil.getCurrentUser();
        Integer fromStatus = breedReport.getStatus();
        Boolean flagBreedReport = false;
        Map<String , Object> map = Maps.newHashMap();
        if(toStatus != null && !fromStatus.equals(toStatus)){
            breedReport.setStatus(toStatus);
            flagBreedReport = breedReportDao.update(breedReport);
            map.put("flagBreedReport",flagBreedReport);

            ReportHandleResume reportHandleResume = new ReportHandleResume();
            reportHandleResume.setReportId(breedReport.getId());
            reportHandleResume.setReportNumber(breedReport.getNumber());
            reportHandleResume.setType(DocumentsType.QUARANTINE_ORIGIN_AREA.value());//0:代表产地检疫
            reportHandleResume.setUserId(loginUser.getId());
            reportHandleResume.setUserName(loginUser.getName());
            reportHandleResume.setFromStatus(fromStatus);
            reportHandleResume.setToStatus(toStatus);

            reportHandleResumeDao.create(reportHandleResume);
            map.put("reportHandleResumeId",reportHandleResume.getId());
        }else{
            flagBreedReport = breedReportDao.update(breedReport);
            map.put("flagBreedReport",flagBreedReport);
        }
        List<String> markNumbers = breedReport.getEarTagNumbers();
        if(markNumbers != null && !markNumbers.isEmpty()){
            Map<String , Object> map1 = Maps.newHashMap();
            map1.put("markNumbers",markNumbers);
            map1.put("isSelected",2);
            animalMarkDao.updateMarks(map1);
        }
        return map;
    }

    /**
     * 产地检疫--政府端的
     * @param breedReport 产地检疫单据的养殖端的对象
     * @param breedReportSurveyRecord 产地检疫政府端的对象
     * @param toStatus 到状态
     * @return Map<String , Object>
     */
    @Transactional
    public Map<String ,Object> updateBreedReportAndSurveyRecord(BreedReport breedReport, BreedReportSurveyRecord breedReportSurveyRecord, Integer toStatus) throws IOException {
        LoginUser loginUser = UserUtil.getCurrentUser();
        Integer fromStatus = breedReport.getStatus();
        Boolean flagBreedReport =  false;
        Boolean flagBreedReportSurveyRecord = false;
        Map<String , Object> map = Maps.newHashMap();
        List<Map<String , Object>> list = breedReport.getFromStables();
        if(toStatus != null && !fromStatus.equals(toStatus)){

            if(breedReportSurveyRecord.getId() == null){
                breedReportSurveyRecord.setReportId(breedReport.getId());
                breedReportSurveyRecordDao.create(breedReportSurveyRecord);//创建
                map.put("breedReportSurveyRecordId",breedReportSurveyRecord.getId());
            }else {
                flagBreedReportSurveyRecord = breedReportSurveyRecordDao.update(breedReportSurveyRecord);//更新
                map.put("flagBreedReportSurveyRecord",flagBreedReportSurveyRecord);
            }
            breedReport.setStatus(toStatus);
            flagBreedReport = breedReportDao.update(breedReport);
            map.put("flagBreedReport",flagBreedReport);

            ReportHandleResume reportHandleResume = new ReportHandleResume();
            reportHandleResume.setReportId(breedReport.getId());
            reportHandleResume.setReportNumber(breedReport.getNumber());
            reportHandleResume.setType(DocumentsType.QUARANTINE_ORIGIN_AREA.value());
            reportHandleResume.setUserId(loginUser.getId());
            reportHandleResume.setUserName(loginUser.getName());
            reportHandleResume.setFromStatus(fromStatus);
            reportHandleResume.setToStatus(toStatus);
            reportHandleResumeDao.create(reportHandleResume);//履历表操作
            map.put("reportHandleResumeId",reportHandleResume.getId());
            //如果toStatus 为 以勘察的时候 的处理
            if(toStatus.equals(BreedReportStatus.STAY_LICENSE.value())){
                if(breedReportSurveyRecord.getHarmlessTreatmentQuantity() > 0){
                    Harmless harmless = buildHarmless(breedReport,breedReportSurveyRecord,loginUser);
                    harmlessDao.create(harmless);
                    map.put("harmlessId",harmless.getId());
                    breedReportSurveyRecord.setHarmlessId(harmless.getId());
                    breedReportSurveyRecord.setHarmlessNumber(harmless.getNumber());
                    breedReportSurveyRecordDao.update(breedReportSurveyRecord);
                }
            }

            if(toStatus.equals(BreedReportStatus.HAS_LICENSE.value())){
                if(Strings.isNullOrEmpty(breedReport.getSourceJson())){
                    if(list == null || list.isEmpty()){
                        ProductionReport productionReport = buildProductionReport(breedReport,null,null,null);
                        productionReportDao.create(productionReport);
                        map.put("productionReportId",productionReport.getId());
                        BreedFactory breedFactory = new BreedFactory();
                        breedFactory.setId(productionReport.getBreedFactoryId());
                        breedFactory.setStockQuantity(productionReport.getChangeQuantity());

                        breedFactoryDao.updateFromSC(breedFactory);
                    }else {
                        for(Map<String , Object> stableInfo : list){
                            ProductionReport productionReport = buildProductionReport(breedReport,Long.valueOf((int) stableInfo.get("stableId")),(String)stableInfo.get("stableNumber"),(int)stableInfo.get("stableQuantity"));
                            productionReportDao.create(productionReport);

                            BreedFactoryStable breedFactoryStable = new BreedFactoryStable();
                            breedFactoryStable.setId(productionReport.getStableId());
                            breedFactoryStable.setQuantity(productionReport.getChangeQuantity());
                            breedFactoryStableDao.updateFromSC(breedFactoryStable);
                        }
                        BreedFactory breedFactory = new BreedFactory();
                        breedFactory.setId(breedReport.getBreedFactoryId());
                        breedFactory.setStockQuantity(breedReport.getQuantity());

                        breedFactoryDao.updateFromSC(breedFactory);
                    }
                    if (breedReport.getIsToLocal() == 2){
                        butcherAdmissionInspectionDao.create(buildButcherAdmissionInspection(breedReport,breedReportSurveyRecord,loginUser));
                    }
                }
                //耳标出库
                List<String> earTagNumbers = breedReport.getEarTagNumbers();
                if(earTagNumbers == null){
                    BreedReport breedReport1 = breedReportDao.findById(breedReport.getId());
                    earTagNumbers = breedReport1.getEarTagNumbers();
                }
                Map<String , Object> map1 = Maps.newHashMap();
                map1.put("markNumbers",earTagNumbers);
                map1.put("status",AnimalMarkStatus.USED.value());
                map1.put("outedAt",new Date());

                animalMarkDao.updateMarks(map1);
            }
            if (toStatus.equals(BreedReportStatus.DISAPPROVE.value()) || toStatus.equals(BreedReportStatus.NO_LICENSE.value())) {
                List<String> earTagNumbers = breedReport.getEarTagNumbers();
                if(earTagNumbers == null){
                    BreedReport breedReport1 = breedReportDao.findById(breedReport.getId());
                    earTagNumbers = breedReport1.getEarTagNumbers();
                }
                Map<String , Object> map1 = Maps.newHashMap();
                map1.put("markNumbers",earTagNumbers);
                map1.put("isSelected",1);
                animalMarkDao.updateMarks(map1);
            }
        }
        return map;
    }

    /**
     * 构建生产记录的对象
     * @param breedReport 产地检疫申报单对象
     * @return ProductionReport
     */
    private ProductionReport buildProductionReport(BreedReport breedReport,Long stableId, String stableNumber,Integer stableQuantity) {
        ProductionReport productionReport = new ProductionReport();

        Integer breedType = breedReport.getBreedType();
        Integer breedSecondType = 0;
        Integer breedThirdType = 0;
        LoginUser loginUser = UserUtil.getCurrentUser();
        String prefix = "SSC";
        prefix = Utils.createPrefix(prefix,loginUser);//单据编号前缀的开头字母 和 当前用户
        String number = Utils.create(prefix,productionReportDao.findCurrentMaxNumber(prefix));//要在表中拿到当前最大的Number号
        productionReport.setNumber(number);

        productionReport.setRelateId(breedReport.getId());
        productionReport.setRelateNumber(breedReport.getNumber());
        productionReport.setBreedType(breedType);
        if(stableId != null){
            BreedFactoryStable breedFactoryStable = breedFactoryStableDao.findById(stableId);
            breedSecondType = breedFactoryStable.getBreedSecondType();
            breedThirdType = breedFactoryStable.getBreedThirdType();
            productionReport.setStableId(stableId);
            productionReport.setStableNumber(stableNumber);
            productionReport.setChangeQuantity(0-stableQuantity);
            productionReport.setOutQuantity(stableQuantity);
            productionReport.setArea(breedFactoryStable.getStableType());
        }else {
            breedSecondType = breedReport.getBreedSecondType();
            breedThirdType = breedReport.getBreedThirdType();
            productionReport.setOutQuantity(breedReport.getQuantity());
            productionReport.setChangeQuantity( 0 - breedReport.getQuantity());
        }
        productionReport.setBreedSecondType(breedSecondType);
        productionReport.setBreedThirdType(breedThirdType);
        productionReport.setInQuantity(0);
        productionReport.setBirthQuantity(0);
        productionReport.setBreedFactoryId(breedReport.getBreedFactoryId());
        productionReport.setBreedFactoryName(breedReport.getBreedFactoryName());
        productionReport.setDeathQuantity(0);
        productionReport.setDate(new Date());
        productionReport.setUnit(breedReport.getUnit());
        productionReport.setStatus(ProductionReportStatus.FINISHED.value());
        productionReport.setDeleteFlag(DocumentsDeleteFlag.NORMAL.value());
        return productionReport;
    }

    /**
     * 构建无害化单据的对象
     * @param breedReport 产地检疫的 养殖端数据对象
     * @param breedReportSurveyRecord 产地检疫-- 政府端的数据对象
     * @return Harmless
     */
    private Harmless buildHarmless(BreedReport breedReport, BreedReportSurveyRecord breedReportSurveyRecord ,LoginUser loginUser) {
        Harmless harmless = new Harmless();
        String prefix = "WN";
        prefix = Utils.createPrefix(prefix,loginUser);
        String number = Utils.create(prefix,harmlessDao.findCurrentMaxNumber(prefix));

        harmless.setNumber(number);
        harmless.setReportId(breedReport.getId());//关联单据的id
        harmless.setReportNumber(breedReport.getNumber());//关联单据的编码
        harmless.setReportType(DocumentsType.QUARANTINE_ORIGIN_AREA.value());//关联单据的类型
        harmless.setApplyReportId(breedReport.getApplyReportId());
        harmless.setApplyReportName(breedReport.getApplyReportName());
        harmless.setBreedFactoryId(breedReport.getBreedFactoryId());
        harmless.setBreedFactoryName(breedReport.getBreedFactoryName());
        harmless.setButcherFactoryName(breedReport.getButcherFactoryName());
        harmless.setIsLocal(breedReport.getIsToLocal());
        harmless.setAnimalType(breedReport.getBreedType());
        harmless.setUnit(breedReport.getUnit());
        harmless.setTreatment(breedReportSurveyRecord.getHarmlessTreatment());
        harmless.setQuantity(breedReportSurveyRecord.getHarmlessTreatmentQuantity().floatValue());
        harmless.setQuarantineUserId(breedReportSurveyRecord.getSurveyUserId());
        harmless.setQuarantineUserName(breedReportSurveyRecord.getSurveyUserName());
        harmless.setFactoryOwnerName(breedReport.getOwner());
        harmless.setStatus(HarmlessStatus.UNCOMMITTED.value());
        harmless.setDeleteFlag(DocumentsDeleteFlag.NORMAL.value());
        return harmless;
    }

    /**
     * 生成入场监督检查的单据（产地检疫发证是自动生成）
     * @param breedReport 产地检疫--养殖申报表 对象
     * @param breedReportSurveyRecord 产地检疫--政府处理检查表  对象
     * @return 入场监督检查的对象
     */
    private ButcherAdmissionInspection buildButcherAdmissionInspection(BreedReport breedReport, BreedReportSurveyRecord breedReportSurveyRecord ,LoginUser loginUser) throws IOException {
        ButcherAdmissionInspection butcherAdmissionInspection = new ButcherAdmissionInspection();
        String prefix = "N";
        prefix = Utils.createPrefix(prefix,loginUser);
        String number = Utils.create(prefix,butcherAdmissionInspectionDao.findCurrentMaxNumber(prefix));

        butcherAdmissionInspection.setNumber(number);
        butcherAdmissionInspection.setStatus(ButcherAdmissionInspectionStatus.UNCOMMITTED.value());
        butcherAdmissionInspection.setUserId(loginUser.getId());
        butcherAdmissionInspection.setUserName(loginUser.getName());
        butcherAdmissionInspection.setOwner(breedReport.getOwner());
        butcherAdmissionInspection.setOwnerMobile(breedReport.getOwnerMobile());
        butcherAdmissionInspection.setButcherFactoryId(breedReport.getButcherFactoryId());
        butcherAdmissionInspection.setButcherFactoryName(breedReport.getButcherFactoryName());
        butcherAdmissionInspection.setBreedReportId(breedReport.getId());
        butcherAdmissionInspection.setBreedReportNumber(breedReport.getNumber());
        butcherAdmissionInspection.setIsLocal(breedReport.getIsToLocal());
        butcherAdmissionInspection.setButcherSelected(-1);
        butcherAdmissionInspection.setDate(new Date());
        butcherAdmissionInspection.setUnit(breedReport.getUnit());
        butcherAdmissionInspection.setProductType(breedReport.getBreedType());
        butcherAdmissionInspection.setQuantity(breedReportSurveyRecord.getQualifiedQuantity());
        butcherAdmissionInspection.setSourceId(breedReport.getBreedFactoryId());
        butcherAdmissionInspection.setSourceName(breedReport.getBreedFactoryName());
        butcherAdmissionInspection.setEarTagNumbers(breedReport.getEarTagNumbers());
        butcherAdmissionInspection.setRemainderEars(breedReport.getEarTagNumbers());
        butcherAdmissionInspection.setClinicalExamination(breedReportSurveyRecord.getExamination());
        butcherAdmissionInspection.setHasAnimalIdentify(breedReportSurveyRecord.getHasAnimalIdentify());
        butcherAdmissionInspection.setQuarantineCertNumber(breedReportSurveyRecord.getQuarantineCertNumber());
        butcherAdmissionInspection.setQuarantineCertPhotoJson(breedReportSurveyRecord.getQuarantineCertPhotoJson());
        butcherAdmissionInspection.setQualifiedQuantity(breedReportSurveyRecord.getQualifiedQuantity());
        butcherAdmissionInspection.setUnqualifiedQuantity(0);
        butcherAdmissionInspection.setRemainder(breedReportSurveyRecord.getQualifiedQuantity());
        butcherAdmissionInspection.setSlaughterings(0);
        butcherAdmissionInspection.setDeleteFlag(DocumentsDeleteFlag.NORMAL.value());
        return butcherAdmissionInspection;
    }

    @Transactional
    public Boolean update(BreedReport breedReport) {

        return breedReportDao.update(breedReport);
    }

}
